<?php
namespace api\know\controller;

use api\know\model\MaterialModel;
use api\know\model\TeachingMaterialContentModel;
use api\know\model\ResourceModel;
use api\know\model\QuestionModel;
use api\know\model\PaperModel;
use api\know\model\PaperQuestionModel;
use api\know\model\PaperCategoryModel;
use api\know\model\PaperQuestionUserModel;
use api\know\model\PaperUserModel;
use api\know\controller\KnowRestUserController;
use think\facade\Db;

class PaperController extends KnowRestUserController
{
    public function detail()
    {
        $uuid = $this->request->param('uuid', '');
		if (empty($uuid))
        {
            $this->error('章节不能为空!');
        }

        $p_wh[] = ['is_delete', '=', 0];
        $p_wh[] = ['is_enable', '=', 1];
        $p_wh[] = ['uuid', '=', $uuid];

        $p = PaperModel::where($p_wh)->field(PaperModel::$QueryField)->find();
		if (empty($p)) 
		{
			$this->error('试卷不存在!');
		}

        $pc_wh[] = ['paper_uuid', '=', $p['uuid']];
        $categorys = PaperCategoryModel::where($pc_wh)->field(PaperCategoryModel::$QueryField)->select()->toArray();

        $pq_wh[] = ['paper_uuid', '=', $p['uuid']];
        $questions = PaperQuestionModel::where($pq_wh)->field(PaperQuestionModel::$QueryField)->select();
		
		$uid = $this->getUserId('uid');
        $q_u_wh[] = ['paper_uuid', '=', $uuid];
        $q_u_wh[] = ['uid', '=', $uid];
		$answers = PaperQuestionUserModel::where($q_u_wh)->field(PaperQuestionUserModel::$QueryField)->select()->toArray();

		$type_arr = ['single', 'multiple', 'fill'];
        foreach ($categorys as &$v) 
        {
            $v['questionList'] = [];
            foreach ($questions as &$q) 
            {
                if ($q['paper_category_uuid'] === $v['uuid'])
                {
					$qus = QuestionModel::getQuestionComposite($q['question_uuid']);

					if (in_array($qus['basic']['type_code'], $type_arr))
					{
						$aw = false;
						foreach($answers as $v6)
						{
							if ($v6['question_uuid'] === $qus['basic']['uuid'])
							{
								$aw = $v6;break;
							}
						}
						if ($aw)
						{
							$qus['user_answer'] = $aw['answer'] ? $aw['answer'] : $aw['text_answer'];
						}
					}
					else
					{
						foreach($qus['children'] as &$v7)
						{
							$aw = false;
							foreach($answers as $v6)
							{
								if ($v7['basic']['uuid'] === $v6['question_uuid'])
								{
									$aw = $v6;break;
								}
							}
							if ($aw)
							{
								$v7['user_answer'] = $aw['answer'] ? $aw['answer'] : $aw['text_answer'];
							}
						}
					}

                    array_push($v['questionList'], $qus);
                }
            }
        }
		$p['question'] = $categorys;
        $this->success('请求成功!', $p);
    }
	
    public function answer()
    {
        $uuid = $this->request->param('uuid', '');
		$answer = $this->request->param('answer');
		if (empty($uuid))
        {
            $this->error('试卷不能为空!');
        }
		else if (empty($answer))
        {
            $this->error('答案不能为空!');
        }

        $p_wh[] = ['is_delete', '=', 0];
        $p_wh[] = ['is_enable', '=', 1];
        $p_wh[] = ['uuid', '=', $uuid];

        $p = PaperModel::where($p_wh)->field(PaperModel::$QueryField)->find();
		if (empty($p)) 
		{
			$this->error('试卷不存在!');
		}

        $pq_wh[] = ['paper_uuid', '=', $p['uuid']];
        $questions = PaperQuestionModel::where($pq_wh)->field(PaperQuestionModel::$QueryField)->select()->toArray();
		$paper_question_uuids = array_map(function($item) {
			return $item['question_uuid'];
		}, $questions);

		// 处理试卷汇总信息
        $uid = $this->getUserId('uid');
        $u_p_wh[] = ['paper_uuid', '=', $uuid];
        $u_p_wh[] = ['uid', '=', $uid];
        $p_u = PaperUserModel::where($u_p_wh)->find();
		if (empty($p_u))
		{
			$p_u = [
				'uid' => $uid,
				'paper_uuid' => $uuid,
				'score' => 0,
				'commit_datetime' => date("Y-m-d H:i:s"),
				'create_user' => $this->user['user_nickname'],
			];
			$row = PaperUserModel::create($p_u);
		}
		// 处理试卷汇总信息

		// 处理试卷试题信息
        $u_q_wh[] = ['paper_uuid', '=', $uuid];
        $u_q_wh[] = ['uid', '=', $uid];
        $q_u_a = PaperQuestionUserModel::where($u_q_wh)->select()->toArray();

		$q_wh[] = ['is_delete', '=', 0];
        $q_wh[] = ['is_enable', '=', 1];
		$q_wh[] = ['uuid', 'in', array_map(function($item) {
			return $item['question_uuid'];
		}, array_values($answer))];
        $question_list = QuestionModel::where($q_wh)->field(QuestionModel::$QueryField)->select()->toArray();
		
		// 处理试卷试题信息
		$q_u_a_a = [];
		$t = ['single', 'multiple'];
		Db::startTrans();
		try 
		{
			foreach($answer as $v)
			{
				$question_uuid = $v['question_uuid'];
				$aw = $v['answer'];
				
				if (in_array($question_uuid, $paper_question_uuids) === false)
				{
					continue;
				}
				$q = false;
				foreach($q_u_a as $k1=>$v1)
				{
					if ($question_uuid === $v1['question_uuid'])
					{
						$q = $v1;break;
					}
				}
				if ($q)
				{
					PaperQuestionUserModel::where('id', $q['id'])->save([
						'answer' => in_array($q['question_type'], $t) ? $aw : '',
						'text_answer' => in_array($q['question_type'], $t) ? '' : $aw
					]);
				}
				else
				{
					$q_item = false;
					foreach($question_list as $k1=>$v1)
					{
						if ($question_uuid === $v1['uuid'])
						{
							$q_item = $v1;break;
						}
					}
					array_push($q_u_a_a, [
						'uid' => $uid,
						'paper_uuid' => $uuid,
						'question_uuid' => $question_uuid,
						'question_type' => $q_item['type_code'],
						'answer' => in_array($q_item['type_code'], $t) ? $aw : '',
						'text_answer' => in_array($q_item['type_code'], $t) ? '' : $aw,
						'create_user' => $this->user['user_nickname'],
					]);
				}
			}
			
			if (empty($q_u_a_a) === false)
			{
				PaperQuestionUserModel::insertAll($q_u_a_a);
			}
			Db::commit();
		} 
		catch (\Exception $e) 
		{
            Db::rollback();
            $this->error($e->getMessage());
        }
		$this->log('106');
        $this->success('保存成功!');
    }

}
